package net.da.server;

import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.da.client.dto.DaErrorData;
import net.da.client.dto.LoginRequestData;
import net.da.client.dto.LoginResponseData;
import net.da.client.service.AuthorizeService;
import net.da.processor.DaError;
import net.da.processor.ProcessorProvider;
import net.da.processor.authorization.LoginProcessor;
import net.da.processor.authorization.io.LoginRequest;
import net.da.processor.authorization.io.LoginResponse;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class AuthorizeServiceImpl extends RemoteServiceServlet implements
		AuthorizeService { 

	public static final String AUTHORIZATION_CODE = "AUTHORIZATION_CODE";
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	public LoginResponseData loginUser(LoginRequestData logingRequestData) {
		
		
		// TODO:ABE
		HttpServletRequest request = getThreadLocalRequest();
		HttpSession session = request.getSession();
		ProcessorProvider processorProvider = ProcessorProvider
				.getInstance(true);
		LoginProcessor loginProcessor = processorProvider.getLoginProcessor();

		LoginRequest logingRequest = convertLoginRequestData(logingRequestData);
		LoginResponse loginResponse = loginProcessor.processRequest(
				logingRequest, null);
		session.setAttribute(AUTHORIZATION_CODE, loginResponse
				.getAuthorizationCode());
		LoginResponseData loginResponseData = convertLoginResponse(loginResponse);
		return loginResponseData;
	}

	private LoginResponseData convertLoginResponse(LoginResponse loginResponse) {
		// TODO Auto-generated method stub
		LoginResponseData loginResponseData = new LoginResponseData();
		List errors = loginResponse.getErrors();
		for (Iterator iterator = errors.iterator(); iterator.hasNext();) {
			DaError error = (DaError) iterator.next();
			DaErrorData errorData = convertError(error);
			loginResponseData.addError(errorData);
		}
		
		loginResponseData.setAuthorizationCode(loginResponse.getAuthorizationCode());
		loginResponseData.setAuthenticationFailed(loginResponse.isAuthenticationFailed());		
		loginResponseData.setWrongOrganisationUnit(loginResponse.isWrongOrganisationUnit());		
		return loginResponseData;
	}

	private LoginRequest convertLoginRequestData(
			LoginRequestData logingRequestData) {
		
		LoginRequest loginRequest = new LoginRequest();
		loginRequest.setAuthroisationCode(logingRequestData.getAuthroisationCode());
		loginRequest.setOrganizationUnit(logingRequestData.getOrganizationUnit());
		loginRequest.setPassword(logingRequestData.getPassword());
		loginRequest.setUserName(logingRequestData.getUserName());
		return loginRequest;
	}

	private DaErrorData convertError(DaError daError) {
		DaErrorData daErrorData = new DaErrorData();
		daErrorData.setMessage(daError.getMessage());
		return daErrorData;
	}

}
